<template>
  <div>
    <el-tree
      ref="tree"
      :data="list"
      node-key="id"
      :props="{label:'name'}"
      show-checkbox
      default-expand-all
      check-strictly
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button>取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeList } from '@/utils/departments'
import { getRolesDetail, assignPage } from '@/api/settings'

export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    async hSubmit() {
      try {
        // 这里使用了ElementUI的固定语法获取复选框的状态
        const permIds = this.$refs.tree.getCheckedKeys()
        // 发送请求，请求带所在角色的id + 权限点id的数组
        const res = await assignPage({ id: this.id, permIds })
        console.log(res)
        // 子传父自定义事件关闭窗口
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    async loadPermissionList() {
      try {
        // 获取所有角色的列表
        const res = await getPermissionList()
        // 获取单个角色的权限详情
        const perId = await getRolesDetail(this.id)
        console.log(perId, 'perId')
        // 通过elementUI的固定语法通过id来选中权限复选框
        // 传入固定的id
        this.$refs.tree.setCheckedKeys(perId.data.permIds)
        console.log(res)
        this.list = tranListToTreeList(res.data)
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>

<style>

</style>
